<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/2
 * Time: 13:20
 */

namespace app\api\controller\android\v11;


use app\api\model\PollingModel;
use think\Config;
use think\Controller;
use app\api\model\Authority;
use think\Exception;
use  app\api\model\OrderModel;
use think\Request;
use app\api\model\Envelopes;

/*
 * 合同签约所有流程
 */

class CostCalculation extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;


    public function _initialize()
    {
        $this->model = new Authority();

        $this->us = Authority::check(1);

    }

    public function share($orderModel, $order_id)
    {

        $offer = $orderModel::offer($order_id);
        if (!empty($offer['mainContract'])) {
            $pdf = contractPdf($order_id);
            if ($pdf['code'] != 200) {
                r_date(null, 300, $pdf['msg']);
            }
            $u['url']                       = $pdf['data']['image_url'].'?t='.time();
            $do                             = [
                'agency' => 0,
                'data' => [
                    $u,
                ],
            ];
        }
        if ($offer['agency']) {
            $agentPdf   = agentContractPdf($order_id);
            $img['url'] = $agentPdf['data']['image_url'].'?t='.time();
            if ($agentPdf['code'] != 200) {
                r_date(null, 300, $pdf['msg']);
            }
            $do['agency'] = 1;
            array_push($do['data'], $img);

        }

        sendOrder($order_id);
        return $do;

    }

    /*
     * 代购合同
     */


    /*
    * 合同问题
    */
    public function ContractIssues($type = 1)
    {

        $data = [
            [
                'title' => '墙面翻新',
                'type' => 0,
                'check' => 0,
            ],
            [
                'title' => '室内渗漏水',
                'type' => 1,
                'check' => 0,
            ],
            [
                'title' => '建筑渗漏水',
                'type' => 2,
                'check' => 0,
            ],
            [
                'title' => '局部改造',
                'type' => 3,
                'check' => 0,
            ],
            [
                'title' => '其它',
                'type' => 4,
                'check' => 0,
            ],
        ];
        if ($type == 2) {
            return $data;
        } else {
            r_date($data, 200);
        }

    }


    /**
     * 新板合同页面报价显示
     */
    public function ContractDisplay(Envelopes $envelopes, OrderModel $orderModel)
    {
        $data      = Authority::param(['order_id']);
        $op        = db('order')->where(['order.order_id' => $data['order_id']])
            ->join('sign', 'order.order_id=sign.order_id', 'left')
            ->join('contract co', 'order.order_id=co.orders_id', 'left')
            ->field('order.state,sign.*,co.con_time as conTime,order.contacts')
            ->find();
        $envelopes = $envelopes
            ->where(['envelopes.type' => 1, 'envelopes.ordesr_id' => $data['order_id']])
            ->with(['CapitalList', 'CapitalList.specsList', 'OrderList'])
            ->find();

        $capitalList = $envelopes['capital_list'];
        $mainPayTpe2 = [];
        foreach ($capitalList as $k => $item) {
            $mainPayTpe2[$k]['money']      = 0;
            $mainPayTpe2[$k]['proportion'] = 0;
            $mainPayTpe2[$k]['type']       = $item['capital_id'];
            $mainPayTpe2[$k]['check']      = 0;
            if ($item['capital_id'] == $op['main_mode_type1']) {
                $mainPayTpe2[$k]['proportion'] = $op['main_pay_type1'];
                $mainPayTpe2[$k]['money']      = $op['main_pay_type1_money'];
                $mainPayTpe2[$k]['check']      = 1;
            }
            $mainPayTpe2[$k]['title'] = $item['projectTitle'];

        }

        //交互标准
        $capital_id = array_column($capitalList, 'capital_id');

        $purchasingAllMoney = [];
        $mainAllMoney       = [];

        foreach ($capitalList as $list) {
            if ($list['agency'] == 1) {
                $purchasingAllMoney[] = $list['allMoney'];
            }
            if ($list['agency'] == 0) {
                $mainAllMoney[] = $list['allMoney'];
            }

        }
        $allMoney             = array_sum($mainAllMoney) - $envelopes['give_money'] + $envelopes['expense'];
        $purchasingAllMoney   = array_sum($purchasingAllMoney) - $envelopes['purchasing_discount'] + $envelopes['purchasing_expense'];
        $auxiliaryProjectList = db('auxiliary_project_list')->whereIn('capital_id', $capital_id)->whereNull('delete_time')->field('auxiliary_id,id,capital_id')->select();

        //质保卡
        $warranty_collection             = \db('warranty_collection')->where('warranty_collection.envelopes_id', $envelopes['envelopes_id'])->where('warranty_collection.pro_types', 0)->join('warranty', 'warranty.id=warranty_collection.warranty_id', 'left')->where('warranty_collection.order_id', $envelopes['ordesr_id'])->field('warranty.title,warranty_collection.years,warranty_collection.type,warranty_collection.warranty_id,warranty_collection.id')->select();
        $orderInfo['orderId']            = $data['order_id'];
        $orderInfo['orderState']         = $op['state'];
        $orderInfo['contractState']      = !empty($op['autograph']) ? 1 : 2;
        $orderInfo['warranty']           = count($warranty_collection);
        $orderInfo['standard']           = !empty(count($auxiliaryProjectList)) ? 1 : 0;
        $orderInfo['sumMainMoney']       = $allMoney;
        $orderInfo['sumPurchasingMoney'] = $purchasingAllMoney;
        $orderInfo['envelopesId']        = $envelopes['envelopes_id'];
        $orderInfo['throughId']          = $envelopes['through_id'];

        $engineering = explode(',', $op['engineering']);

        $listArray = $this->ContractIssues(2);
        if (is_array($engineering)) {
            foreach ($engineering as $lis) {
                foreach ($listArray as $k => $item) {
                    if ($lis == $item['type']) {
                        $listArray[$k]['check'] = 1;
                    }
                }

            }
        }


        $UserInfo['projectContent'] = $listArray;
        $UserInfo['day']            = $envelopes['gong'];
        $UserInfo['startTime']      = empty(trim($op['addtime'])) ? '' : date('Y-m-d', $op['addtime']);
        $UserInfo['endTime']        = empty($UserInfo['startTime']) ? '' : date('Y-m-d', strtotime($UserInfo['startTime'] . '+' . $UserInfo['day'] . ' day'));
        $UserInfo['isCheckTime']    = empty($UserInfo['startTime']) ? 1 : 0;
        $UserInfo['moneyDay']       = $op['overdue_days'];


        $MainCollectionInfo['pay']          = !empty($op['pay_type']) ? $op['pay_type'] : 3;
        $MainCollectionInfo['deposit']      = !empty($op['deposit']) ? $op['deposit'] : 0;
        $MainCollectionInfo['depositMoney'] = !empty($op['ding']) ? $op['ding'] : 0;

        $mainPayTpe1 = [
            [
                'title' => "签合同当日",
                'type' => 1,
                'money' => !empty($op['main_pay_money']) ? $op['main_pay_money'] : 0,
                'proportion' => !empty($op['main_mode_type']) ? $op['main_mode_type'] : 0,
                'check' => 0,
            ],
            [
                'title' => "开工当日",
                'type' => 2,
                'money' => !empty($op['main_pay_money']) ? $op['main_pay_money'] : 0,
                'proportion' => !empty($op['main_mode_type']) ? $op['main_mode_type'] : 0,
                'check' => 0,
            ],
        ];
        foreach ($mainPayTpe1 as $k => $list) {

            if (!empty($op['main_mode_type'])) {
                if ($op['main_mode_type'] == $list['type']) {
                    $mainPayTpe1[$k]['check'] = 1;
                }
            } else {
                if ($k == 0) {
                    $mainPayTpe1[$k]['check'] = 1;
                }

            }
        }
        $mainPayTpe3[] = [
            'title' => "全部项目",
            'type' => 1,
            'money' => !empty($op['main_pay_type2_money']) ? $op['main_pay_type2_money'] : 0,
            'proportion' => !empty($op['main_mode_type2']) ? $op['main_mode_type2'] : 0,
        ];
        foreach ($mainPayTpe3 as $k => $list) {
            if (!empty($op['main_mode_type2'])) {
                if ($op['main_mode_type2'] == $list['type']) {
                    $mainPayTpe3[$k]['check'] = 1;
                }
            } else {
                if ($k == 0) {
                    $mainPayTpe3[$k]['check'] = 1;
                }
            }
        }

        $MainCollectionInfo['mainPayTpe1']     = $mainPayTpe1;
        $MainCollectionInfo['mainPayTpe2']     = $mainPayTpe2;
        $MainCollectionInfo['mainPayTpe3']     = $mainPayTpe3;
        $MainCollectionInfo['pay']             = !empty($op['main_pay_once']) ? $op['main_pay_once'] : 3;
        $MainCollectionInfo['additionalTerms'] = !empty($op['additional']) ? $op['additional'] : '';
        $MainCollectionInfo['childProportion'] = [0.4,0.3,0.2];
        $purchasingPayTpe1                     = [
            [
                'title' => "签合同当日",
                'type' => 1,
                'money' => !empty($op['purchasing_pay__type_money']) ? $op['purchasing_pay__type_money'] : 0,
                'proportion' => !empty($op['purchasing_pay_type']) ? $op['purchasing_pay_type'] : 0,
                'check' => 0,
            ],
            [
                'title' => "开工当日",
                'type' => 2,
                'money' => !empty($op['purchasing_pay__type_money']) ? $op['purchasing_pay__type_money'] : 0,
                'proportion' => !empty($op['purchasing_pay_type']) ? $op['purchasing_pay_type'] : 0,
                'check' => 0,
            ],
        ];
        $purchasingTpe2      []                = [
            'title' => "全部项目",
            'type' => 1,
            'check' => 1,
            'money' => !empty($op['purchasing_pay_type1_money']) ? $op['purchasing_pay_type1_money'] : 0,
            'proportion' => !empty($op['purchasing_pay_type1']) ? $op['purchasing_pay_type1'] : 0,
        ];
        foreach ($purchasingPayTpe1 as $k => $list) {
            if (!empty($op['purchasing_mode_type'])) {
                if ($op['purchasing_mode_type'] == $list['type']) {
                    $purchasingPayTpe1[$k]['check'] = 1;
                }
            } else {
                if ($k == 0) {
                    $purchasingPayTpe1[$k]['check'] = 1;
                }

            }

        }
        foreach ($purchasingTpe2 as $k => $list) {
            if (!empty($op['purchasing_mode_type1'])) {
                if ($op['purchasing_mode_type1'] == $list['type']) {
                    $purchasingTpe2[$k]['check'] = 1;
                }
            } else {
                if ($k == 0) {
                    $purchasingTpe2[$k]['check'] = 1;
                }

            }

        }

        $PurchasingInfo['pay']                       = !empty($op['purchasing_pay_once']) ? $op['purchasing_pay_once'] : 1;
        $PurchasingInfo['additionalTerms']           = !empty($op['additional_agent']) ? $op['additional_agent'] : '';
        $PurchasingInfo['purchasingPayTpe1']         = $purchasingPayTpe1;
        $PurchasingInfo['purchasingTpe2']            = $purchasingTpe2;
        $CollectionInformation['MainCollectionInfo'] = $MainCollectionInfo;
        $CollectionInformation['PurchasingInfo']     = $PurchasingInfo;

        $contractInfo['username']     = empty($op['username'])?$op['contacts']:$op['username'];
        $contractInfo['idnumber']     = $op['idnumber'];
        $contractInfo['address']      = $op['addres'];
        $contractInfo['contractpath'] = $op['contractpath'];
        $contractInfo['agency_img']   = $op['agency_img'];
        $contractInfo['overdueDays']  = $op['overdue_days'];
        $contractInfo['conTime']      = empty($op['conTime']) ? '' : date('Y-m-d H:i', $op['conTime']);
        if (!empty($op['sign_id'])) {
            if (empty($op['autograph']) && empty($op['contractpath']) && empty($op['agency_img'])) {
                $do = $this->share($orderModel, $data['order_id']);
            } else {
                $do = [
                    'agency' => 0,
                    'data' => [],
                ];
                if (!empty($op['contractpath'])) {
                    $img['url'] = $op['contractpath'];
                    array_push($do['data'], $img);
                }
                if (!empty($op['agency_img'])) {
                    $img['url']   = $op['agency_img'];
                    $do['agency'] = 1;
                    array_push($do['data'], $img);
                }
                $id=db('contract')->insert(['orders_id'=>$data['order_id'],'contracType'=>2,'con_time'=>$op['con_time']]);
                $orderModel->where(['order_id'=>$data['order_id']])->update(['contract_id'=>$id]);
                $contractInfo['conTime']      =  date('Y-m-d H:i', $op['con_time']);
            }
            if (empty($do['data'])) {
                $do = null;
            }
            $UserInfo['data'] = $do;
        } else {
            $UserInfo['data'] = null;
        }
        $op = ['userInfo' => $contractInfo, 'orderInfo' => $orderInfo, 'contractInfo' => $UserInfo, 'collectionInformation' => $CollectionInformation];

        r_date($op, 200);
    }

    public function ContractAllocation()
    {
        $pamer = Authority::param(['type', 'id']);
        if ($pamer['id'] == 1) {
            switch ($pamer['type']) {
                case 1:
                    $data = ['one' => 1];
                    break;
                case 2:
                    $data = ['one' => 0.5, 'two' => 0.5];
                    break;
                default:
                    $data = ['one' => 0.5, 'two' => 0.4, 'three' => 0.1];
            }
        } else {
            switch ($pamer['type']) {
                case 1:
                    $data = ['one' => 1];
                    break;
                case 2:
                    $data = ['one' => 0.5, 'two' => 0.5];
                    break;

            }
        }

        r_date($data, 200);
    }

    /**
     * 电子合同
     */
    public function sign(OrderModel $orderModel, Envelopes $envelopes)
    {
        $data      = Authority::param(['data']);
        $listArray = json_decode($data['data'], true);
        $op        = db('order')
            ->join('sign', 'order.order_id=sign.order_id', 'left')
            ->field('order.assignor,order.order_no,sign.*')
            ->where(['order.order_id' => $listArray['orderInfo']['orderId']])
            ->find();

        $projectContent = [];
        foreach ($listArray['contractInfo']['projectContent'] as $list) {
            if ($list['check'] == 1) {
                $projectContent[] = $list['type'];
            }
        }

        $mainPayTpe1      = '';
        $mainPayTpe1Money = '';
        $mainPayTpe1Bi    = '';
        foreach ($listArray['collectionInformation']['MainCollectionInfo']['mainPayTpe1'] as $list) {
            if ($list['check'] == 1) {
                $mainPayTpe1      = $list['type'];
                $mainPayTpe1Money = $list['money'];
                $mainPayTpe1Bi    = $list['proportion'];
            }
        }
        $mainPayTpe2      = '';
        $mainPayTpe2Money = '';
        $mainPayTpe2Bi    = '';
        foreach ($listArray['collectionInformation']['MainCollectionInfo']['mainPayTpe2'] as $list) {
            if ($list['check'] == 1) {
                $mainPayTpe2      = $list['type'];
                $mainPayTpe2Money = $list['money'];
                $mainPayTpe2Bi    = $list['proportion'];
            }
        }
        $mainPayTpe3      = '';
        $mainPayTpe3Money = '';
        $mainPayTpe3Bi    = '';
        foreach ($listArray['collectionInformation']['MainCollectionInfo']['mainPayTpe3'] as $list) {
            if ($list['check'] == 1) {
                $mainPayTpe3      = $list['type'];
                $mainPayTpe3Money = $list['money'];
                $mainPayTpe3Bi    = $list['proportion'];
            }
        }
        $purchasingPayTpe1      = '';
        $purchasingPayTpe1Money = '';
        $purchasingPayTpe1Bi    = '';
        foreach ($listArray['collectionInformation']['PurchasingInfo']['purchasingPayTpe1'] as $list) {
            if ($list['check'] == 1) {
                $purchasingPayTpe1      = $list['type'];
                $purchasingPayTpe1Money = $list['money'];
                $purchasingPayTpe1Bi    = $list['proportion'];
            }
        }
        $purchasingPayTpe2      = '';
        $purchasingPayTpe2Money = '';
        $purchasingPayTpe2Bi    = '';
        foreach ($listArray['collectionInformation']['PurchasingInfo']['purchasingTpe2'] as $list) {
            if ($list['check'] == 1) {
                $purchasingPayTpe2      = $list['type'];
                $purchasingPayTpe2Money = $list['money'];
                $purchasingPayTpe2Bi    = $list['proportion'];
            }
        }
        $userId = $this->us['user_id'];
        if ($op['assignor'] != $op['user_id']) {
            $userId = $op['assignor'];
        }

        $sign = [
            'idnumber' => isset($listArray['userInfo']['idnumber'])?$listArray['userInfo']['idnumber']:'',
            'username' => $listArray['userInfo']['username'],
            'order_id' => $listArray['orderInfo']['orderId'],
            'user_id' => $userId,
            'confirm' => 3,
            'addtime' => empty($listArray['contractInfo']['isCheckTime']) ? strtotime($listArray['contractInfo']['startTime']) :'' ,
            'uptime' => empty($listArray['contractInfo']['isCheckTime']) ? strtotime($listArray['contractInfo']['endTime']): '',
            'addres' => $listArray['userInfo']['address'],
            'main_deposit' => $listArray['collectionInformation']['MainCollectionInfo']['deposit'],
            'ding' => !empty($listArray['collectionInformation']['MainCollectionInfo']['deposit']) ? $listArray['collectionInformation']['MainCollectionInfo']['depositMoney'] : 0,
            'main_pay_once' => $listArray['collectionInformation']['MainCollectionInfo']['pay'],
            'main_mode_type' => $mainPayTpe1,
            'main_pay_type' => $mainPayTpe1Bi,
            'main_pay_money' => $mainPayTpe1Money,
            'main_mode_type1' =>$listArray['collectionInformation']['MainCollectionInfo']['pay']==1 || $listArray['collectionInformation']['MainCollectionInfo']['pay']==2?0: $mainPayTpe2,
            'main_pay_type1' => $listArray['collectionInformation']['MainCollectionInfo']['pay']==1 || $listArray['collectionInformation']['MainCollectionInfo']['pay']==2?0:$mainPayTpe2Bi,
            'main_pay_type1_money' => $listArray['collectionInformation']['MainCollectionInfo']['pay']==1 || $listArray['collectionInformation']['MainCollectionInfo']['pay']==2?0:$mainPayTpe2Money,
            'main_pay_type2' =>$listArray['collectionInformation']['MainCollectionInfo']['pay']==1 ?0:$mainPayTpe3Bi,
            'main_pay_type2_money' => $listArray['collectionInformation']['MainCollectionInfo']['pay']==1?0:$mainPayTpe3Money,
            'main_mode_type2' => $listArray['collectionInformation']['MainCollectionInfo']['pay']==1?0:$mainPayTpe3,
            'purchasing_pay_once' => $listArray['collectionInformation']['PurchasingInfo']['pay'],
            'purchasing_mode_type' => $purchasingPayTpe1,
            'purchasing_pay_type' => $purchasingPayTpe1Bi,
            'purchasing_pay__type_money' => $purchasingPayTpe1Money,
            'purchasing_mode_type1' => $listArray['collectionInformation']['PurchasingInfo']['pay']==1?0:$purchasingPayTpe2,
            'purchasing_pay_type1' =>  $listArray['collectionInformation']['PurchasingInfo']['pay']==1?0:$purchasingPayTpe2Bi,
            'purchasing_pay_type1_money' =>  $listArray['collectionInformation']['PurchasingInfo']['pay']==1?0:$purchasingPayTpe2Money,
            'additional' => $listArray['collectionInformation']['MainCollectionInfo']['additionalTerms'],
            'additional_agent' => $listArray['collectionInformation']['PurchasingInfo']['additionalTerms'],
            'engineering' => implode(',', $projectContent),
            'con_time' => time(),
            'contract' => $op['order_no'],
            'overdue_days' => isset($listArray['contractInfo']['moneyDay']) ? $listArray['contractInfo']['moneyDay'] : 0,
        ];

        if (!empty($op['sign_id'])) {
            db('sign')->where(['sign_id' => $op['sign_id']])->update($sign);
        } else {
            db('sign')->insertGetId($sign);
        }

        $envelopes->where('ordesr_id', $listArray['orderInfo']['orderId'])->where('type', 1)->Update(['gong' => $listArray['contractInfo']['day']]);
        $do = $this->share($orderModel, $listArray['orderInfo']['orderId']);
        r_date($do, 200);
    }

    /*
     * 合同重签
     */
    public function Countersign()
    {
        $data = Authority::param(['orderId']);
        db('contract')->where('orders_id', $data['orderId'])->delete();
        db('sign')->where('order_id', $data['orderId'])->update(['autograph'=>'','contractpath'=>'','agency_img'=>'']);
        r_date(null, 200);
    }


}